import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import './medicalhomepage.css'
import { AtSearchBar, AtIcon, AtGrid, AtAccordion, AtTag, AtDrawer, AtRadio, AtActionSheet, AtActionSheetItem } from 'taro-ui'
import reactMixin from 'react-mixin';
import myJs from './medicalhomepageJs.js'
import app from '../../../main.js'

export default class MedicalHomePage extends Component {

  config = {
    navigationBarTitleText: '病历管理'
  }

  constructor() {
    super(...arguments);
    this.state = {
      open: false,
      show_label: false,
      show_month: false,
      show_sort: false,
      keyword: '',
      labels: [],
      label_ids: '',
      month: '',
      sort: 2,
      projects: [],
      cases: [],
      months: [
        {id: 0,  value: '', label: '全部'},
        {id: 1,  value: '01', label: '1月'},
        {id: 2,  value: '02', label: '2月'},
        {id: 3,  value: '03', label: '3月'},
        {id: 4,  value: '04', label: '4月'},
        {id: 5,  value: '05', label: '5月'},
        {id: 6,  value: '06', label: '6月'},
        {id: 7,  value: '07', label: '7月'},
        {id: 8,  value: '08', label: '8月'},
        {id: 9,  value: '09', label: '9月'},
        {id: 10, value: '10', label: '10月'},
        {id: 11, value: '11', label: '11月'},
        {id: 12, value: '12', label: '12月'}
      ],
      isOpenedCaseSheetItem: false,
      lastProject: [],
      settime:'0',
      docid:this.$router.params.id
    };
  }

  init() {
    this.getProjects();
    this.getLastProject();
    app.showShareMenu();
  }

  componentDidShow() {
    this.getLabels();
    this.reset();
    this.getCases();
    this.handelIsOpenedCaseSheetItem(false);
  }

  getProjects() {
    let me = this;
    app.get('web/project/many', {offset: 0, length: 2}, function(res) {
      me.setState({
        projects: res.data.result
      });
    });
  }

  getLabels() {
    let me = this;
    app.get('web/caselabel/many', {}, function(res) {
      let labels = res.data.result;
      for (let i = 0; i < labels.length; i++) {
        labels[i].active = false;
      }
      me.setState({
        labels: labels
      });
    });
  }

  // 打开标签弹窗
  open_label() {
    this.setState({
      show_label: true,
      show_month: false,
      show_sort: false,
      isOpenedCaseSheetItem: false
    });
  }

  // 打开月份弹窗
  open_month() {
    this.setState({
      show_month: true,
      show_label: false,
      show_sort: false,
      isOpenedCaseSheetItem: false
    });
  }

  // 打开排序弹窗
  open_sort() {
    this.setState({
      show_sort: true,
      show_label: false,
      show_month: false,
      isOpenedCaseSheetItem: false
    });
  }

  // 点击标签
  clickLabel(id) {
    let me = this;
    let labels = this.state.labels;
    for (let i = 0; i < labels.length; i++) {
      var item = labels[i];
      if (item.id == id) {
        item.active = !item.active;
      }
    }
    this.reset();
    this.setState({
      labels: labels,
      keyword: '',
      label_ids: me.getLabelIds(labels)
    }, () => {
      me.getCases();
    });
  }

  // 标签全部置灰
  resetLabels() {
    let labels = this.state.labels;
    for (let i = 0; i < labels.length; i++) {
      let item = labels[i];
      item.active = false;
    }
    this.setState({
      labels: labels
    });
  }

  // 点击月份
  selectMonth(value) {
    let me = this;
    this.reset();
    this.setState({
      month: value,
      keyword: ''
    }, () => {
      me.getCases()
    });
  }

  // 点击排序
  selectSort(value) {
    let me = this;
    me.reset();
    this.setState({
      sort: value
    }, () => {
      me.getCases();
    })
    me.close_all();
  }

  reset() {
    this.offset = 0;
    this.isFinish = false;
    this.setState({
      cases: []
    });
  }

  close_label() {
    this.close_all();
  }

  close_month() {
    this.close_all();
  }

  close_sort() {
    this.close_all();
  }

  close_all() {
    this.setState({
      show_sort: false,
      show_label: false,
      show_month: false
    });
  }

  getLabelIds(list) {
    let label_ids = '';
    for (let i = 0; i < list.length; i++) {
      var item = list[i];
      if (item.active == false) {
        continue;
      }
      label_ids += item.id + ',';
    }
    if (label_ids.length > 0) {
      label_ids = label_ids.substr(0, label_ids.length - 1);
    }
    return label_ids;
  }

  isFinish = false; // 加载更多是否结束
  offset = 0;
  length = 20;
  total = 0;

  getCases() {
    let me = this;
    let data = {
      offset: this.offset,
      length: this.length,
      label_ids: this.state.label_ids,
      month: this.state.month,
      sort: this.state.sort,
      keyword: this.state.keyword
    }
    app.get("web/case/history_project_cases", data, function(res) {
      if (res.data.result.list.length > 0) {
        let cases = me.state.cases;
        cases = cases.concat(res.data.result.list);
        me.total = res.data.result.total;
        me.setState({cases: cases});
      } else {
        me.isFinish = true;
      }
    });
  }

  // 搜索
  search() {
    let me = this;

    if(this.state.settime == 0){
        me.setState({
            settime:1
        })
        setTimeout(res =>{
            me.setState({
                settime:0
            })
        },400)

        me.reset();
        me.resetLabels();
        me.setState({
          label_ids: '',
          month: '',
          sort: 2
        }, () => {
            me.getCases();
        });
    }
  }

  //

  // 上拉加载
  onReachBottom() {
    if ((this.offset + this.length) < this.total) {
      app.toast('正在加载中...');
    } else {
      app.toast('没有更多数据了');
    }
    if (!this.isFinish) {
      this.offset = this.offset + this.length;
      this.getCases();
    }
  }

  go = (item, index) => {
    switch (index) {
      case 0:
        app.navigateTo('../../patientlables/pages/labelmanagemedical/labelmanagemedical');
        break;
      case 1:
        // app.navigateTo('../createCase/createCase');
        this.handelIsOpenedCaseSheetItem(true);
        break;
      case 2:
        // app.toast('暂未开放，敬请期待');
        app.navigateTo('../../patientlables/pages/xuanzexiezuobingli/xuanzexiezuobingli');
        break;
    }
  }

  getLastProject() {
    let me = this;
    app.get('web/project/last_project', {}, function(res) {
      me.setState({
        lastProject: res.data.result
      });
    });
  }

  handelIsOpenedCaseSheetItem(v) {
    this.setState({
      isOpenedCaseSheetItem: v
    });
  }


  goto(url) {
    this.handelIsOpenedCaseSheetItem(false);
    app.navigateTo(url);
  }

  render() {
    const case_list = this.state.cases.map((item) => {
      return <View className='medical-record' onClick={this.navigateTo.bind(this, '../editCase/editCase?id='+item.id)}>
              {
                (item.status && (item.status == '初审待修改' || item.status == '终审待修改'))
                &&
                <View className='status bg_red'>{item.status}</View>
              }
              {
                (item.status && (item.status != '初审待修改' && item.status != '终审待修改'))
                &&
                <View className='status bg_green'>{item.status}</View>
              }
              <View className='first-line'>
                <Text className='fl name'>{item.patient_name}</Text>
                <Text className='fl'>{item.gender}</Text>
                <Text className='fl'>{item.age}岁</Text>
              </View>
              {
                (item.diagnosis != 'null' && item.diagnosis)
                &&
                <View className='second-line'>{item.diagnosis}</View>
              }
              <View className='third-line'>
                <View className='float'>
                  <AtIcon value='bullet-list' size='22' color='#cccccc' className='icon'></AtIcon>{item.code}
                </View>
                <View className='float'>
                  <AtIcon value='calendar' size='20' color='#cccccc' className='icon'></AtIcon> {item.created_at}
                </View>
                {
                  item.project_name &&
                  <View className='float project_name' style='margin-right: 0'>
                    <Text className='point'></Text>
                    <Text className='pointe-text project_txt'>{item.project_name}</Text>
                  </View>
                }
              </View>
            </View>
    })

    const project_list = this.state.projects.map((item) => {
      return <View className='pj' onClick={this.navigateTo.bind(this, '../../project/pages/projectdetails/projectdetails?id='+item.id+'&docid='+this.state.docid)}>
              <Image className='pj_img' src={app.getPath(item.image)}></Image>
              <View className='project_title'>{item.name}</View>
            </View>
    })

    const arr = this.state.labels.map((item) => {
      console.log(33);
      return <AtTag
          className='label'
          circle
          type='primary'
          active={item.active}
          onClick={this.clickLabel.bind(this, item.id)}
        >
          {item.name}
        </AtTag>;
    })

    return (
      <View className='medical-home'>
        <AtSearchBar
          className='search'
          value={this.state.keyword}
          onChange={this.handleChange.bind(this, 'keyword')}
          onActionClick={this.search.bind(this)}
        />
        <AtGrid className='jump-btn' mode='rect' columnNum={3} onClick={this.go.bind(this)} data={
          [
            {
              image: app.imageUri + 'img/biaoqian.png',
              value: '病历标签'
            },
            {
              image: app.imageUri + 'img/tianjia.png',
              value: '添加病历'
            },
            {
              image: app.imageUri + 'img/zhuanjia.png',
              value: '病历协作'
            },
          ]
        } />
        <View className='realworld'>
          真实世界项目
          <View className='arrow' onClick={this.navigateTo.bind(this, '../../project/pages/projecthomepage/projecthomepage')}>
            <Text>更多</Text>
            <AtIcon value='chevron-right' size='24' color='#999999'></AtIcon>
          </View>
        </View>
        <View className='pj_list'>
          {project_list}
        </View>
        <View className='realworld'>
          所有病历
        </View>
        <AtDrawer show={this.state.show_label} mask onClose={this.close_label.bind(this)}>
          {arr}
        </AtDrawer>
        <AtDrawer show={this.state.show_month} mask onClose={this.close_month.bind(this)}>
          <AtRadio
            options={this.state.months}
            value={this.state.month}
            onClick={this.selectMonth.bind(this)}
          />
        </AtDrawer>
        <AtActionSheet isOpened={this.state.show_sort} onClose={this.close_sort.bind(this)}>
          <AtActionSheetItem onClick={this.selectSort.bind(this, 1)}>
            由早到晚
          </AtActionSheetItem>
          <AtActionSheetItem onClick={this.selectSort.bind(this, 2)}>
            由晚到早
          </AtActionSheetItem>
          <AtActionSheetItem onClick={this.selectSort.bind(this, 3)}>
            姓名排序
          </AtActionSheetItem>
        </AtActionSheet>
        <View className='select-fun'>
          <AtAccordion
            open={this.state.open}
            title='标签筛选'
            className='fun'
            right
            onClick={this.open_label.bind(this)}
          >
          </AtAccordion>
          <AtAccordion
            open={this.state.open}
            title='创建月份'
            className='fun'
            right
            onClick={this.open_month.bind(this)}
          >
          </AtAccordion>
          <AtAccordion
            open={this.state.open}
            title='排序方式'
            className='fun last'
            onClick={this.open_sort.bind(this)}
          >
          </AtAccordion>
        </View>
        {case_list}
        <AtActionSheet isOpened={this.state.isOpenedCaseSheetItem} cancelText='取消' onCancel={this.handelIsOpenedCaseSheetItem.bind(this, false)}>
          {
            this.state.lastProject.map((item)=>{
              return <AtActionSheetItem onClick={this.goto.bind(this, '../createCase/createCase?type=病例&project_id='+item.id)}>
                {item.name}
              </AtActionSheetItem>
            })
          }
          <AtActionSheetItem onClick={this.goto.bind(this, '../createCase/createCase?type=病历')}>
            个人病历
          </AtActionSheetItem>
        </AtActionSheet>
      </View>
    )
  }
}
reactMixin.onClass(MedicalHomePage, myJs);
